﻿using Kingdee.BOS.App.Core;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Text;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace DzInfo.SerivesPlugin.GYD
{
    [Description("GYD库存销售订单保存自动提交审核"), HotUpdate]
    public class AutoSubmitAudit : AbstractOperationServicePlugIn
    {
        public override void AfterExecuteOperationTransaction(AfterExecuteOperationTransaction e)
        {
            base.AfterExecuteOperationTransaction(e);
            var obj2 = e.DataEntitys.FirstOrDefault();
            if (obj2 == null) { return; }
            string billTypeNumber = obj2["BillTypeId"] == null ? "" : (obj2["BillTypeId"] as DynamicObject)["number"].ToString();
            if (billTypeNumber.Equals("XSDD001_SYS") || billTypeNumber.Equals("XSDD17_SYS") || billTypeNumber.Equals("XSDD005_SYS"))
            {
                // 假设金蝶提供如下API（示例写法，需确认实际API）
                var isOrderChange2 = this.Option.GetOperationParameter(); //GetExtendOptionValue<bool>("IsOrderChange");
                var isCheck = this.Option;
                // 使用示例
                if (TryGetOptionValue("IsOrderChange", out bool isOrderChange))
                {
                    //Console.WriteLine($"Order change status: {isOrderChange}");
                    // 在业务逻辑中使用 isOrderChange
                }
                var isok = isOrderChange;
                if (!isok)
                {
                    var saveResult = this.OperationResult;
                    // 筛选出保存成功的单据内码
                    var successPKs = saveResult.OperateResult.Where(o => o.SuccessStatus == true).Select(x => x.PKValue).Distinct().ToArray();
                    if (successPKs.Length == 0)
                    {
                        // 没有保存成功的结果，直接退出
                        return;
                    }
                    // 提交处理
                    var submitService = new SubmitService();
                    var submitResult = submitService.Submit(Context, BusinessInfo, successPKs, FormOperationEnum.Submit.ToString(), Option.Copy());
                    var isExit = CheckResult(saveResult, submitResult);
                    saveResult.MergeResult(submitResult);
                    if (isExit)
                    {
                        // 有提交失败的结果，直接退出
                        return;
                    }
                    // 审核处理
                    // 再次筛选中保存成功并且提交也成功的结果
                    successPKs = saveResult.OperateResult.Where(o => o.SuccessStatus == true).Select(x => x.PKValue).Distinct().ToArray();
                    if (successPKs.Length == 0)
                    {
                        // 没有提交成功的结果，直接退出
                        return;
                    }
                    var paras = new List<object>() { "1" }; //审核所需参数
                    var auditPKs = successPKs.Select(x => new KeyValuePair<object, object>(x, "")).ToList();
                    var statusService = new SetStatusService();
                    var auditResult = statusService.SetBillStatus(Context, BusinessInfo, auditPKs, paras, FormOperationEnum.Audit.ToString(), Option.Copy());
                    isExit = CheckResult(saveResult, auditResult);
                    saveResult.MergeResult(auditResult);
                    if (isExit)
                    {
                        // 有审核失败的结果，直接退出
                        return;
                    }
                    // 操作完成后刷新单据状态数据
                    var billStatusField = this.BusinessInfo.GetBillStatusField();
                    var billStatusPropertyName = billStatusField.PropertyName;
                    var objs = new BusinessDataReader(Context).Load(e.DataEntitys.Select(o => o[0]).ToArray()
                        , BusinessInfo.GetSubBusinessInfo(new List<string>(new[] { billStatusField.Key })).GetDynamicObjectType());
                    foreach (var obj in objs)
                    {
                        var saveObj = e.DataEntitys.FirstOrDefault(o => o[0].ToString() == obj[0].ToString());
                        if (saveObj != null)
                        {
                            saveObj[billStatusPropertyName] = obj[billStatusPropertyName];
                        }
                    }
                }
            }

        }

        private bool TryGetOptionValue<TValue>(string key, out TValue value)
        {
            value = default;
            try
            {
                // 1. 修正字段名为"dict"（根据截图实际字段名）
                var dictField = this.Option.GetType().GetField("dict",
                    System.Reflection.BindingFlags.NonPublic |
                    System.Reflection.BindingFlags.Instance);

                // 2. 正确处理字典类型（Dictionary<string, object>）
                if (dictField?.GetValue(this.Option) is Dictionary<string, object> dictionary)
                {
                    // 3. 安全获取并转换值
                    if (dictionary.TryGetValue(key, out object objValue) && objValue is TValue)
                    {
                        value = (TValue)objValue;
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                // 4. 添加日志记录以便调试
                //Logger.Error($"获取Option值失败: {ex.Message}");
            }
            return false;
        }

        private bool CheckResult(IOperationResult saveResult, IOperationResult nextResult)
        {
            if (nextResult == null)
            {
                saveResult.IsSuccess = false;
                return true;
            }
            if (!nextResult.IsSuccess)
            {
                // 操作失败
                saveResult.IsSuccess = false;
                return true;
            }
            if (nextResult.InteractionContext != null)
            {
                // 交互异常
                saveResult.IsSuccess = false;
                return true;
            }
            var failResults = nextResult.OperateResult.Where(e => e.SuccessStatus == false).ToArray();
            if (failResults.Length > 0 || nextResult.ValidationErrors.Count > 0)
            {
                // 操作异常，校验异常
                saveResult.IsSuccess = false;
                return true;
            }
            return false;
        }
    }
}
